<?php

namespace App\Http\Middleware;

use App\Exceptions\BusinessException;
use App\Common\Constant;
use App\Common\JwtAuth;
use App\Common\ResponseCode;
use Carbon\Carbon;
use Closure;
use Illuminate\Http\Request;

/**
 * 客户JWT授权验证中间件
 *
 * @package App\Http\Middleware
 * @author WangBin
 * @date 2021-06/11
 */
class CustomerAuth
{
    private $authHeader = 'Authorization';
    /**
     * 会员调用服务接口权限验证
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     * @throws
     */
    public function handle(Request $request, Closure $next)
    {
        // auth请求头
        if(!$request->hasHeader('Authorization')) {
            throw new BusinessException(ResponseCode::API_AUTH_FORBIDDEN);
        }
        // 获取token
        $tokenStr = $request->header('Authorization');
        $token = str_replace('Bearer ', '', $tokenStr);
        if(empty($tokenStr) || !str_contains($tokenStr, 'Bearer ') || empty($token)) {
            throw new BusinessException(ResponseCode::API_AUTH_FORBIDDEN);
        }
        // 校验token
        $ret = JwtAuth::getInstance()->setToken($token)->validate();
        if(empty($ret)) {
            throw new BusinessException(ResponseCode::API_AUTH_FORBIDDEN);
        }
        // 校验时间戳及token类型和user_id
        if($ret['expired_at'] < Carbon::now()->timestamp || $ret['type'] != Constant::JWT_TYPE_CUSTOMER || empty($ret['entity_id'])) {
            throw new BusinessException(ResponseCode::API_AUTH_FAIL);
        }
        // 注入Request customer_id
        $request->offsetSet('customer_id', $ret['entity_id']);
        $request->offsetSet('customer_name', $ret['entity_name']);
        return $next($request);
    }
}
